<template>
  <div class="upload-section">
    <Upload
      :fileList="fileList"
      list-type="picture-card"
      class="upload-comp"
      :maxCount="maxCount"
      :accept="accept"
      @remove="handleRemove"
      @download="handleDownload"
      :beforeUpload="handleBeforeUpload"
      :customRequest="handleCustomRequest"
    >
      <template v-if="fileList.length < maxCount">
        <LoadingOutlined v-if="loading" />
        <div class="upload-icon" v-else>
          <PlusOutlined class="icon-plus" />
        </div>
      </template>
      <template #itemRender="{ file, actions }">
        <div class="item-picture" :style="{ backgroundImage: `url(${getItemBackground(file)})` }">
          <a class="item-delete" href="javascript:;" @click="actions.remove">
            <DeleteOutlined />
          </a>
          <a class="item-delete" href="javascript:;" @click="actions.download">
            <DownloadOutlined />
          </a>
        </div>
        <Tooltip>
          <template #title>
            <span>{{ file.name || file.originRiderName }}</span>
          </template>
          <div class="item-text">{{ attachNameEllipsis(file.name || file.originRiderName) }}</div>
        </Tooltip>
      </template>
    </Upload>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, unref } from 'vue'
import { Upload, message, Tooltip, Form } from 'ant-design-vue'
import {
  LoadingOutlined,
  DeleteOutlined,
  DownloadOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import bg_pdf from '../../assets/images/uploadAttach/pdf.png'
import { preAuthDownloadFile } from '@/api/home'
import { downloadFile } from '@/utils/file'
const emit = defineEmits(['update'])

// modelValue为File对象
const props = defineProps({
  modelValue: {
    type: Array,
    default: []
  },
  uploadApi: {},
  deleteApi: {},
  maxCount: {
    type: [String, Number],
    default: 1000000
  },
  path: '',
  type: '',
  accept: '',
  fileTypeMess: '' // 文件类型错误提示
})

// 表单上下文注入,用于自定义组件和form一起使用
const formItemContext = Form.useInjectFormItemContext()

// 文件列表
const fileList = ref(props.modelValue)

// 生成uuid

const uuid = ref(crypto.randomUUID())
watch(
  () => props.modelValue,
  (newValue) => {
    fileList.value = newValue
  }
)
onMounted(() => {
  console.log('fileList', props.modelValue)
})

// 加载状态
const loading = ref(false)

// 获取图片的背景
function getItemBackground(file) {
  const suffix = getSuffix(file?.name || file?.originRiderName)
  switch (suffix) {
    case 'png':
    case 'jpg':
      return file.bgUrl
    default: {
      return bg_pdf
    }
  }
}

// 上传文件改变后的回调函数
function handleBeforeUpload(file) {
  // 上传大小限制为100MB
  const isLt100M = file.size / 1024 / 1024 < 100
  if (!isLt100M) {
    message.error('单个文件大小不能超过100MB')
  }
  return isLt100M
}

// 在删除附件后的回调函数
function handleRemove(file) {
  const index = fileList.value.indexOf(file)
  const newFileList = fileList.value.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
  triggerChange(fileList.value)
}

// 点击下载后的回调
function handleDownload(file) {
  preAuthDownloadFile(file.fileId).then((res) => {
    downloadFile(res)
  })
}

// 自定义上传方法
function handleCustomRequest(data) {
  const { file, onSuccess, onError } = data
  // 判断 文件类型 并给错误提示
  // if (!checkFileType(file)) return
  console.log('file', file)
  const uploadApi = props.uploadApi
  loading.value = true
  const formData = new FormData()
  formData.append('file', file)
  formData.append('riderType', '09')
  formData.append('businessCode', unref(uuid))
  uploadApi(formData)
    .then((res) => {
      const resData = res.data
      const url = resData.filePath
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        file.bgUrl = reader?.result
        file.url = url
        file.fileId = resData.fileId
        file.fileName = resData.fileName
        file.fileSuffix = resData.fileSuffix
        file.fileType = resData.fileType
        fileList.value?.push(file)
        triggerChange(fileList.value)
      }
      loading.value = false
      onSuccess(res)
    })
    .catch((err) => {
      loading.value = false
      message.error(err.message)
      onError(err)
    })
}

// 将组件的改变，触发调用方
function triggerChange(fileList) {
  emit('update', fileList)
  formItemContext.onFieldChange()
}

// 处理附件名称字端截取
function attachNameEllipsis(name) {
  const suffix = `.${getSuffix(name)}`
  return `${name?.slice(0, 2)}... ${suffix}`
}

// 获取后缀
function getSuffix(name) {
  const suffix = `${name?.split('.')?.pop()}`
  return suffix.toLowerCase()
}
// 校验文件格式是否支持 return false 不支持上传 true 支持上传
// 此方法有误，部分文件 type为空,如.msg
function checkFileType(file) {
  const { name, type } = file
  const suffix = `.${getSuffix(name)}`
  const acceptList = props.accept?.split(',')
  // 文件后缀名、MIME在accept中都不存在，文件不支持上传
  if (!acceptList.includes(suffix) && !acceptList.includes(type)) {
    message.error(props.fileTypeMess || '不支持该文件类型！')
    return false
  }

  return true
}
</script>

<style lang="scss" scoped>
.upload-section {
  border-radius: 4px;
  border: 1px solid #dfdfdf;
  padding: 15px;

  .upload-comp ::v-deep(.ant-upload) {
    width: 60px;
    height: 80px;
    border: none;
  }

  .upload-comp ::v-deep(.ant-upload-list-picture-card-container) {
    width: 65px;
    height: 80px;
  }

  .upload-icon {
    width: 60px;
    height: 80px;

    border: 1px dotted #dfdfdf;
    display: flex;
    align-content: center;
    justify-content: center;
    &:hover {
      border: 1px dotted #4d789c;
      background-color: #e8f0f3;
      .icon-plus {
        color: #4d789c;
        font-size: 32px;
      }
    }
    .icon-plus {
      font-size: 32px;
      color: #dfdfdf;
    }
  }

  .item-picture {
    width: 60px;
    height: 80px;
    border-radius: 4px;
    border: 1px solid #dfdfdf;

    background-size: 100% 100%;

    &:hover {
      background-size: 100% 100%;
      cursor: pointer;

      .item-delete {
        visibility: visible;
      }
    }

    .item-delete {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      background-color: rgba(0, 0, 0, 0.5);
      box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.1);
      width: 50%;
      height: 100%;
      color: #fff;
      visibility: hidden;
    }
  }

  .item-text {
    white-space: nowrap;
    font-size: 12px;
    font-family: PingFang-SC-Regular, PingFang-SC;
    font-weight: 400;
    color: #666666;
    transform: scale(0.9);
  }
}
</style>
